// define(function(require) {

var React = require('react');
var Component = React.Component;
var PropTypes = React.PropTypes;
var antd = require('antd');
var { Form, Input, Button, Icon } = antd
var Select = require('jsx!./select')

const FormItem = Form.Item

const New =  '新建'
const Delete =  '删除'
const NotFound = '没有可用选项'
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
}
class SelectSeries extends Component {

  constructor(props) {
    super(props);
    this.state = {
      // 存放 input-select 一组的多个组的数组
      // input-name, select-value
      results: [{ name: '', value: '' }]
    }
  }

  componentWillMount() {
    this.setState({ results: this.props.value })
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.value) {
      this.setState({ results: nextProps.value })
    }
  }

  /**
   * [handleChange 处理单组内的值，可能为name也可能为value]
   * @param  {Number} index [description]
   * @param  {String} data  [description]
   */
  handleChange(index, data) {
    let results = this.state.results
    if (data.target && data.target.value) {
      results[index].name = data.target.value
    } else {
      results[index].value = data
    }
    this.props.onChange(results)
    this.setState({ results })
  }

  handleAddItem() {
    let results = this.state.results || [{ name: '', value: '' }]
    let viewUrl = this.props.viewUrl || ''
    results.push({ name: '', value: viewUrl })
    this.props.onChange(results)
    this.setState({ results })
  }

  handleDeleteItem(index) {
    let results = this.state.results || [{ name: '', value: '' }]
    results.splice(index, 1)
    this.props.onChange(results, index)
    this.setState({ results })
  }

  render() {
    let selectSeries = this.props.value.map((item, index) => {
      return (
        <div key={index} className="ant-form">
          <FormItem {...formItemLayout}>
            <Input value={item.name}
                   placeholder={New}
                   onChange={this.handleChange.bind(this, index)}
            />
          </FormItem>
          <FormItem {...formItemLayout}>
            <Select options={this.props.options}
                    value={item.value}
                    placeholder={this.props.placeholder}
                    notFoundContent={NotFound}
                    onChange={this.handleChange.bind(this, index)}
            />
          </FormItem>
        </div>
      )
    })

    return (
      <div className="select-series">
        { selectSeries }
        <Button className="add-field"
                type="primary"
                title={New}
                onClick={this.handleAddItem.bind(this)}
        >
          <Icon type="plus"/>
        </Button>
      </div>
    )
  }
}

module.exports = SelectSeries

// })
